package com.global.college.base;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.global.college.MainActivity;
import com.global.college.R;
import com.global.college.UserData;
import com.global.college.constants.Constant;
import com.global.college.receiver.ConnectionChangeReceiver;
import com.global.college.utils.AppManagerUtils;
import com.global.college.utils.CommonUtils;
import com.global.college.utils.PermissionHelper;
import com.global.college.utils.PrefUtils;
import com.global.college.widget.HnLoadingDialog;
import com.global.college.widget.HnLoadingLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.Locale;

import butterknife.ButterKnife;

/**
 * Created by fu on 2020/2/22.
 * Describe: 基类
 */
public abstract class BaseActivity extends BaseLayoutActivity {

    protected String TAG = getClass().getSimpleName();
    protected HnLoadingDialog loading;
    protected Bundle mBundle;
    protected Resources.Theme mTheme;
    private ConnectionChangeReceiver mReceiver;// 网络连接状态监听广播

    //权限处理
    private final static int READ_EXTERNAL_STORAGE_CODE = 100;//SD卡
    private final static int WRITE_EXTERNAL_STORAGE_CODE = 101;//SD卡
    protected final static int SETTING_REQUST = 123;
    protected static final int PREMISSION_CANCEL = 0;//权限被取消申请
    protected static final int PREMISSION_SUCCESS = 1;//权限申请成功
    //    protected MusicLoadingView mLoadingView;
    private boolean isTransparent = true;//is full transparent

    public void setTransparent(boolean transparent) {
        isTransparent = transparent;
    }

    //public ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        ButterKnife.bind(this);
        if (!CommonUtils.isPad(this)) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        }
        mBundle = getIntent().getExtras();
        mTheme = getTheme();
        if (PrefUtils.getInt(Constant.PERMISSION_SIZE, 7) != PermissionHelper.getPerSize(this) && null != savedInstanceState) {
            try {
                Class classname = Class.forName("com.global.college.ui.activity.SplashActivity");
                Intent intent = new Intent(this, classname);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            PrefUtils.setInt(Constant.PERMISSION_SIZE, PermissionHelper.getPerSize(this));
        }

        onCreateNew(savedInstanceState);
        getInitData();
        AppManagerUtils.getInstance().addActivity(this);
        //注册网络监听
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        mReceiver = new ConnectionChangeReceiver();
        this.registerReceiver(mReceiver, filter);

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void attachBaseContext(Context newBase) {
        //国际化语言设置
        Resources resources = newBase.getResources();
        Locale locale;
        if (PrefUtils.getString(Constant.Language, "zh").equals("en")) {
            locale = Locale.ENGLISH;
        } else if (PrefUtils.getString(Constant.Language, "zh").equals("tw")) {
            locale = Locale.TRADITIONAL_CHINESE;
        } else {
            locale = Locale.SIMPLIFIED_CHINESE;
        }
        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(locale);
        super.attachBaseContext(newBase.createConfigurationContext(configuration));
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    /**
     * 布局文件id
     *
     * @return
     */
    public abstract int getContentViewId();

    /**
     * 初始化view
     */
    public abstract void onCreateNew(Bundle savedInstanceState);

    /**
     * 初始化data
     */
    public abstract void getInitData();

    protected boolean isStrangePhone() {
        boolean strangePhone = "mx5".equalsIgnoreCase(Build.DEVICE)
                || "Redmi Note2".equalsIgnoreCase(Build.DEVICE)
                || "Z00A_1".equalsIgnoreCase(Build.DEVICE)
                || "hwH60-L02".equalsIgnoreCase(Build.DEVICE)
                || "hermes".equalsIgnoreCase(Build.DEVICE)
                || ("V4".equalsIgnoreCase(Build.DEVICE) && "Meitu".equalsIgnoreCase(Build.MANUFACTURER))
                || ("m1metal".equalsIgnoreCase(Build.DEVICE) && "Meizu".equalsIgnoreCase(Build.MANUFACTURER));

        return strangePhone;
    }

    /**
     * 显示执行进度状态
     */
    public void showDoing(String TAG, DialogInterface.OnCancelListener listener) {
        if (isFinishing()) {
            return;
        }
        if (loading == null) {
            loading = CommonUtils.progressLoading(this, TAG, listener);
//            loading = HnUtils.drawableLoading(this, TAG, listener);
        } else {
            if (loading.isShowing()) {
                loading.cancel();
            }
            loading.setTag(TAG);
            loading.setOnCancelListener(listener);
        }
        loading.show();
    }

    /**
     * 隐藏加载状态或执行状态
     */
    public void done() {
        if (loading != null && loading.isShowing()) {
            loading.dismiss();
        }
    }


    /**
     * 弹出对话框
     */
    public void alert(String title, String description, DialogInterface.OnClickListener listener) {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setMessage(description)
                .setTitle(title)
                .setPositiveButton(getString(R.string.live_ensure), listener)
                .setNegativeButton(getString(R.string.live_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                })
                .create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    /**
     * 根据传入的类(class)打开指定的activity
     *
     * @param pClass
     */
    public void openActivity(Class<?> pClass) {
        Intent itent = new Intent();
        itent.setClass(this, pClass);
        startActivity(itent);
    }

    /**
     * 根据传入的类(class)打开指定的activity
     *
     * @param pClass
     */
    public void openActivity(Class<?> pClass, Bundle bundle) {
        Intent itent = new Intent();
        itent.putExtras(bundle);
        itent.setClass(this, pClass);
        startActivity(itent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (mImmersionBar != null) {
//            mImmersionBar.destroy();
//        }
        unregisterReceiver(mReceiver);// 注销网络广播监听
        AppManagerUtils.getInstance().finishActivity(this);
    }


    /**
     * 改变视图加载状态  需要手动触发
     *
     * @param state
     * @param mHnLoadingLayout
     */
    public void setLoadViewState(int state, HnLoadingLayout mHnLoadingLayout) {
        try {
            if (mHnLoadingLayout == null) return;
            if (state != mHnLoadingLayout.getStatus()) {
                mHnLoadingLayout.setStatus(state);
            }
        } catch (Exception e) {
        }
    }



    /**
     * 展示一个切换动画
     */
    public void showAnimation() {
        final View decorView = getWindow().getDecorView();
        Bitmap cacheBitmap = getCacheBitmapFromView(decorView);
        if (decorView instanceof ViewGroup && cacheBitmap != null) {
            final View view = new View(this);
            view.setBackgroundDrawable(new BitmapDrawable(getResources(), cacheBitmap));
            ViewGroup.LayoutParams layoutParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            ((ViewGroup) decorView).addView(view, layoutParam);
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f);
            objectAnimator.setDuration(300);
            objectAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    ((ViewGroup) decorView).removeView(view);
                }
            });
            objectAnimator.start();
        }
    }

    /**
     * 获取一个 View 的缓存视图
     *
     * @param view
     * @return
     */
    private Bitmap getCacheBitmapFromView(View view) {
        final boolean drawingCacheEnabled = true;
        view.setDrawingCacheEnabled(drawingCacheEnabled);
        view.buildDrawingCache(drawingCacheEnabled);
        final Bitmap drawingCache = view.getDrawingCache();
        Bitmap bitmap;
        if (drawingCache != null) {
            bitmap = Bitmap.createBitmap(drawingCache);
            view.setDrawingCacheEnabled(false);
        } else {
            bitmap = null;
        }
        return bitmap;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //友盟统计
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 判断是否登陆进行跳转
     * <p>
     * 根据传入的类(class)打开指定的activity
     *
     * @param pClass 登录状态要进入的界面
     */
    public void JugeAndOpenActivity(Class<?> pClass, Bundle bundle) {
        String token = UserData.getInstance().getToken();
        if (!TextUtils.isEmpty(token)) {
            Intent intent = new Intent();
            intent.putExtras(bundle);
            intent.setClass(this, pClass);
            startActivity(intent);
        } else {
            //ToastUtils.showToastShort("请您先登录！");
//            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        }

    }

    /**
     * 根据传入的类(class)打开指定的activity
     *
     * @param pClass
     */
    public void JugeAndOpenActivity(Class<?> pClass) {
        String token = UserData.getInstance().getToken();
        if (!TextUtils.isEmpty(token)) {
            Intent itent = new Intent();
            itent.setClass(this, pClass);
            startActivity(itent);
        } else {
            //ToastUtils.showToastShort("请您先登录！");
//            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        }
    }

    public void returnMainActivity(Context mContext){
        Intent intent = new Intent();
        intent.setClass(mContext, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

}
